﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Search
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegate();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //使用并行编程
            try
            {
                Task task_baidu = new Task(() => { SearchinBaidu("https://www.baidu.com/baidu?wd=" + searchText.Text); });
                Task task_bing = new Task(() => { SearchinBing("https://cn.bing.com/search?q=" + searchText.Text); });
                task_baidu.Start();
                task_bing.Start();
            }catch(Exception a)
            {
                MessageBox.Show(a.Message);
            }
            
        }

        private void SearchinBing(string v)
        {
            WebClient webClient = new WebClient();
            //webClient.Encoding = System.Text.Encoding.UTF8;
            byte[] recvdata = webClient.DownloadData(v);
            string response = Encoding.UTF8.GetString(recvdata);
            this.BeginInvoke(new MyDelegate(() => { bingText.Text = response.Substring(0, 200); }));
        }

        private void SearchinBaidu(string v)
        {
            WebClient webClient = new WebClient();
            //webClient.Encoding = System.Text.Encoding.UTF8;
            byte[] recvdata = webClient.DownloadData(v);
            string response = Encoding.UTF8.GetString(recvdata);
            this.BeginInvoke(new MyDelegate(() => { baiduText.Text = response.Substring(0, 200); }));
        }
    }
}
